const https = require('https');
const fs = require('fs');

const downloadFile = (url, filePath) => {
  return new Promise((resolve, reject) => {
    // 创建一个可写流
    const fileStream = fs.createWriteStream(filePath);

    // 请求下载文件
    const request = https.get(url, (response) => {
      console.log('下载开始');

      // 将响应流写入文件流
      response.pipe(fileStream);

      // 监听下载进度
      let receivedBytes = 0;
      response.on('data', (chunk) => {
        receivedBytes += chunk.length;
        console.log(`已接收字节: ${receivedBytes}`);
      });

      fileStream.on('finish', () => {
        console.log('下载完成');
        fileStream.close();
        resolve(filePath);
      });
    });

    // 监听下载错误
    request.on('error', (error) => {
      console.error('下载失败:', error);
      reject(error);
    });

    fileStream.on('error', (error) => {
      console.error('写入文件失败:', error);
      reject(error);
    });
  });
};

const handleDownload = (leftView) => {
  leftView.webContents.session.on('will-download', (event, item, webContents) => {

    // 获取文件名
    const savePath = 'd:/electron/save';
    const fileName = item.getFilename() || 'download.zip';
    const saveFilePath = `${savePath}/${fileName}`;
    
    event.preventDefault();
    event.returnValue = false;

    downloadFile(item.getURL(), saveFilePath)
    .then(() => console.log('文件已保存到:', saveFilePath))
    .catch((error) => console.error('下载失败:', error));
    
  });
};

export default handleDownload;